package com.yaolisheng.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * @author yaolisheng
 * @version 1.0
 * @date 2021/5/5 12:16
 */
public class SerializableUtils {

	/**
	 * 对象序列化
	 */
	public static byte[] toJavaBytes(Object obj) {
		try {
			return write(obj);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	private static byte[] write(Object obj) throws IOException {
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		try (ObjectOutputStream out = new ObjectOutputStream(stream)) {
			out.writeObject(obj);
		}
		return stream.toByteArray();
	}

	/**
	 * 反序列化
	 */
	public static <T> T parseObject(byte[] bytes) {
		try {
			return read(bytes);
		} catch (ClassNotFoundException | IOException e) {
			throw new RuntimeException(e);
		}
	}

	@SuppressWarnings("unchecked")
	private static <T> T read(byte[] bytes)
			throws IOException, ClassNotFoundException {
		try (ObjectInputStream in =
				new ObjectInputStream(new ByteArrayInputStream(bytes))) {
			return (T) in.readObject();
		}
	}

}
